import mysql.connector
import config
import time


class MysqlHelper(object):
    def __init__(self):
        self.conn = self.init_database()
        self.cursor = self.conn.cursor()

    def init_database(self):
        connection = mysql.connector.connect(host=config.HOST,
                                       port=config.PORT,
                                       user=config.USER,
                                       password=config.PASSWORD,
                                       database=config.DATABASE)

        return connection


    def record_op(self, op_time, op_type, buy_platform, sell_platform, price, amount, message):
        print("time: %s, type: %s, buy_platform: %s, sell_platform: %s, price: %s, amount: %s, message: %s" %
              (op_time, op_type, buy_platform, sell_platform, price, amount, message))
        self.cursor.execute("insert into op_record (op_time, op_type, buy_platform, sell_platform, price, amount, message) values (%s, %s, %s, %s, %s, %s, %s)", [op_time, op_type, buy_platform, sell_platform, price, amount, message])
        self.conn.commit()

    def getProfitIn24H(self):
        endTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time())))
        startTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time())-86400))
        self.cursor.execute("select sum(amount) from arbitrager.op_record where op_type='profit' and op_time > %s and op_time < %s"
                            , (startTime, endTime))
        result = self.cursor.fetchall()[0][0]
        if result is None:
            return 0
        else:
            return result


    def end(self):
        self.cursor.close()
        self.conn.close()


